package javamobile.billsplit;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;

import javamobile.utils.Constants;

import android.location.*;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.*;
import android.view.View.*;
import android.widget.*;

public class LocationActivity extends Activity{
	
	public static final String PREFS_NAME = "MyPrefsFile";

	private Button gps;
	private Button wifi;
	private Button confirm;
	private TextView longtitude;
	private TextView latitude;
	
	private double long_;
	private double lat_;
	private String addr;
	
	private TextView address;
	private LocationManager locMgr;
	private Location l;
	
	@SuppressWarnings("unused")
	private LocationListener myLocationListener;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.location);
        gps = (Button) findViewById(R.id.getGPS_LOCATION);
        wifi = (Button) findViewById(R.id.getWIFI_LOCATION);
        confirm = (Button) findViewById(R.id.Confirm_LOCATION);
        latitude = (TextView) findViewById(R.id.Latitude_LOCATION);
        longtitude = (TextView) findViewById(R.id.Longtitude_LOCATION);
        address = (TextView) findViewById(R.id.address_LOCATION);
        
        locMgr = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        
        myLocationListener = new LocationListener() {

			@Override
			public void onLocationChanged(Location loc) {
				if (loc!=null) 
					l.set(loc);
			}

			@Override
			public void onProviderDisabled(String arg0) {
			}

			@Override
			public void onProviderEnabled(String arg0) {
			}

			@Override
			public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			}
        	
        };
        
        //locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, myLocationListener);
        
        
        gps.setOnClickListener(new OnClickListener() {
        	@Override
        	public void onClick(View v) {
        		l = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        		List<String> errors = new ArrayList<String>();  
        		if (l==null) {
        			errors.add("GPS is disabled, getting value from default");
        			lat_ = Constants.getGpsLat();
        			long_ = Constants.getGpsLong();
        		}
        		else {
        			lat_ = l.getLatitude();
        			long_ = l.getLongitude();
        		} 

    			JSONObject addresses = getLocationInfo(lat_, long_);
    			try {
					addr = ((JSONArray)addresses.get("results")).getJSONObject(0).getString("formatted_address");
				} catch (JSONException e) {
					System.out.println("JSONException");
					e.printStackTrace();
				}


        		if (errors.size()!=0) {
        			Intent toError = new Intent(LocationActivity.this, ErrorActivity.class);
        	    	toError.putStringArrayListExtra("errorlist", new ArrayList<String>(errors)); 
        	    	startActivity(toError); 
        		}
    			
    			latitude.setText(String.valueOf(lat_));
        		longtitude.setText(String.valueOf(long_));

        		address.setText(addr);

        	}
        });
        
        wifi.setOnClickListener(new OnClickListener() {
        	@Override
        	public void onClick(View v) {
        		l = locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        		List<String> errors = new ArrayList<String>();  
        		if (l==null) {
        			errors.add("Wifi is disabled, getting value from default");
        			lat_ = Constants.getWifiLat();
        			long_ = Constants.getWifiLong();
        		}
        		else {
        			lat_ = l.getLatitude();
        			long_ = l.getLongitude();
        		} 
				JSONObject addresses = getLocationInfo(lat_, long_);
				try {
					addr = ((JSONArray)addresses.get("results")).getJSONObject(0).getString("formatted_address");
				} catch (JSONException e) {
					System.out.println("JSONException");
					e.printStackTrace();
				}
				
        		if (errors.size()!=0) {
        			Intent toError = new Intent(LocationActivity.this, ErrorActivity.class);
        	    	toError.putStringArrayListExtra("errorlist", new ArrayList<String>(errors)); 
        	    	startActivity(toError); 
        		}
    			
    			latitude.setText(String.valueOf(lat_));
        		longtitude.setText(String.valueOf(long_));

        		address.setText(addr);

        	}
        });
        
       
        
       confirm.setOnClickListener(new OnClickListener() {

        	public void onClick(View v) {
        		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    	    	SharedPreferences.Editor editor = settings.edit();
    	    	editor.putString("location", addr);
    	    	editor.commit();
    	    	finish();
        	}
        });
    }
    
    
    // need to do the menu thing
    
    public static JSONObject getLocationInfo(double lat, double lng) {
        StringBuilder stringBuilder = new StringBuilder();
        try {

        HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&sensor=false");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();


            response = client.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(stringBuilder.toString());
        } catch (JSONException e) {
        	System.out.println("JSONException");
            e.printStackTrace();
        }

        return jsonObject;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
       String menu_str = item.getTitle().toString();
       if (menu_str.equals("Home")) {
    	   Intent toHome = new Intent(LocationActivity.this, HomeActivity.class);
    	   startActivity(toHome);
       }
       return super.onOptionsItemSelected(item); 
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true; 
    }
}
